const { chromium } = require('playwright');
const fs = require('fs');
const path = require('path');
const vscode = require('vscode');

// 创建临时目录
const tempDir = path.join(__dirname, '../.temp');
if (!fs.existsSync(tempDir)) {
  fs.mkdirSync(tempDir, { recursive: true });
}

// 全局测试配置
global.testConfig = {
  tempDir,
  testServerPort: 3000
};

// 初始化浏览器实例
let browser;
beforeAll(async () => {
  browser = await chromium.launch({ headless: true });
});

// 清理资源
afterAll(async () => {
  await browser.close();
});

// VSCode API Mock
jest.mock('vscode', () => {
  const mockCommands = {};
  return {
    commands: {
      registerCommand: jest.fn((name, callback) => {
        mockCommands[name] = callback;
        return { dispose: jest.fn() };
      }),
      executeCommand: jest.fn((name, ...args) => {
        return mockCommands[name]?.(...args);
      })
    },
    window: {
      showInputBox: jest.fn(),
      showInformationMessage: jest.fn(),
      showErrorMessage: jest.fn(),
      createOutputChannel: jest.fn(() => ({
        appendLine: jest.fn(),
        show: jest.fn(),
        dispose: jest.fn()
      })),
      createStatusBarItem: jest.fn(() => ({
        text: '',
        tooltip: '',
        command: '',
        show: jest.fn(),
        hide: jest.fn(),
        dispose: jest.fn()
      }))
    },
    workspace: {
      workspaceFolders: [],
      getConfiguration: jest.fn()
    },
    Uri: {
      file: jest.fn(path => ({ path }))
    },
    ThemeColor: jest.fn()
  };
});

// 测试工具函数
global.createTestPage = async () => {
  const context = await browser.newContext();
  return context.newPage();
};

global.cleanupTempDir = () => {
  if (fs.existsSync(tempDir)) {
    fs.rmdirSync(tempDir, { recursive: true });
  }
};